package com.hcb.service.impl;

import com.hcb.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author 11314
 * @description TODO
 * @date 2022/11/6 19:15
 */
@Service
public class SearchServiceImpl implements SearchService {

    String HOT_SEARCH_KEY="hot:search";
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LoginTreadLocalService service;
    public  String getKeyOfRecentSearch(){
        return "recent:search:"+service.getUserId();
    }
    @Override
    public Set<String> getHotSearch() {
        return redisTemplate.opsForZSet().reverseRange(HOT_SEARCH_KEY,0,10);
    }
    @Override
    public List<String> getRecentSearch() {
                String key=getKeyOfRecentSearch();
        return redisTemplate.opsForList().range(key, 0, -1);
    }
    @Override
    public void addSearchRecord(String search) {
        //添加到个人最近搜索
        String key=getKeyOfRecentSearch();
        redisTemplate.opsForList().remove(key,0,search);
        redisTemplate.opsForList().leftPush(key,search);
        if(redisTemplate.opsForList().size(key)>10){
            redisTemplate.opsForList().rightPop(key);
        }
        //该搜索词条数加一
        redisTemplate.opsForZSet().incrementScore(HOT_SEARCH_KEY,search,1);
    }
}
